<script setup>
import {ref, defineProps, onMounted, watch,onActivated } from "vue";
import axiosInstance from "@/axios/index.js";
import axios from "@/axios/index.js";
import {ElMessage, ElMessageBox} from "element-plus";

// 定义组件接收的props
const props = defineProps({
  studentId: {
    type: String,
    required: true,
  },
  courseId: {
    type: Number,
    required: true,
  },
  homeworkIds: {
    type: Array,
    required: true,
  },
  activeName: {
    required: true,
  }
});

// 用于保存作业主题和学生答案
const homeworkTopics = ref([]);
const studentAnswers = ref([]);
const submitStatus = ref("");
const isSuccess = ref(false);
const isSubmitting = ref(false);
let hasSubmitted = false;

const correctionRecord = ref([])  //存储作业批改记录
let isRecord = false

/**
 * 获取课程作业数据
 */
const fetchCourseHomework = async () => {
  try {
    const response = await axios.get(`/api/v1/front/course/homework`, {
      params: {
        courseId: props.courseId,
        studentId: props.studentId,
      },
    });
    // 筛选有效的作业主题
    homeworkTopics.value = response.data.data
        .filter(item => item.courseHomework && item.studentId)
        .map(item => item.courseHomework.homeworkTopic)
        .filter(topic => topic);

    // console.log(response.data.data);

    // 初始化学生答案数组
    studentAnswers.value = new Array(homeworkTopics.value.length).fill("");

    // 获取学生作业记录
    hasSubmitted = false; // 初始化为未提交
    response.data.data.forEach((record, index) => {
      if (record.studentAnswer) {
        hasSubmitted = true;
        studentAnswers.value[index] = record.studentAnswer;
      }
    });

    correctionRecord.value = response.data.data.map(item => ({
      correctCondition:item.correctJudgment === null ? isRecord = true : isRecord = false,
      teacherComments:item.teacherComments === null ? "还没有哦~" : item.teacherComments,
      correctJudgment:item.correctJudgment === 1 ? "回答正确": item.correctJudgment === 2 ? "回答错误" : "暂无数据"
    }))
    // console.log(correctionRecord.value)


  } catch (error) {
    console.error("获取作业数据失败:", error);
  }
};

// 在组件挂载时获取作业记录
onMounted(fetchCourseHomework);
// 监听 courseId 的变化
/*watch(() => props.courseId, async (newValue) => {
  console.log(1)
  await fetchCourseHomework
});*/

// 组件重新激活时执行

// 监听 courseId 的变化
watch(() => props.courseId, fetchCourseHomework);

// 提交作业记录
const submitHomework = async () => {
  if (hasSubmitted) {
    submitStatus.value = "您已经提交过该作业，无法再次提交。";
    return;
  }

  if (studentAnswers.value.some(answer => answer.trim() === "")) {
    submitStatus.value = "请填写所有答案后再提交。";
    return;
  }

  ElMessageBox.confirm('确定要提交作业吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const records = props.homeworkIds.map((homeworkId,index) => ({
      homeworkId,
      studentId: props.studentId,
      studentAnswer: studentAnswers.value[index] || "",
    }));

    isSubmitting.value = true; // 设置提交状态为正在提交
    try {
      await axiosInstance.put('/api/v1/front/course/updateBatch', records, {
        headers: {
          'content-type': 'application/json',
        },
      });

      ElMessage({   //成功消息提示
        message: '作业提交成功！',
        type: 'success',
        duration: 1000 // 可以设置持续时间，单位为毫秒
      });
      // submitStatus.value = "提交成功！";
      isSuccess.value = true;
      hasSubmitted = true; // 提交成功后更新变量

      // 自动清除提示信息
      setTimeout(() => {
        submitStatus.value = "";
      }, 1000); // 1秒后清除提示
    } catch (error) {
      submitStatus.value = `提交失败: ${error.message || '请重试'}`;
      isSuccess.value = false;
    } finally {
      isSubmitting.value = false; // 重置提交状态
    }
  }).catch(() => {})

};

//重置答案
const reset = () => {
  ElMessageBox.confirm('确认重置答案吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    studentAnswers.value = new Array(homeworkTopics.value.length).fill(""); //清空答案
    submitStatus.value = ""
    hasSubmitted = false
  }).catch(() => {})
}
</script>

<template>
  <div>
    <el-header>
    </el-header>
    <ul>
      <li v-for="(item, index) in homeworkTopics" :key="index" v-if="homeworkTopics.length">
        <p>{{ index + 1 }}、{{ item }}？</p>
        <el-input
            type="textarea"
            placeholder="在这里输入你的答案..."
            v-model="studentAnswers[index]"
            :rows="4"
            :autosize="{ minRows: 4, maxRows: 10 }"
            style="width: 90%;"
        ></el-input>
      </li>
      <el-button v-if="homeworkTopics.length" type="primary" class="el-button" @click="submitHomework"
                 :disabled="isSubmitting || hasSubmitted">提交作业
      </el-button>
      <el-button v-if="homeworkTopics.length" @click="reset" class="el-button" :disabled="isSubmitting || hasSubmitted">
        重置
      </el-button>

      <img src="../../assets/null2.png" v-else/>
    </ul>
    <!-- 提示 -->
    <div v-if="submitStatus" class="submit-status" :class="{'success': isSuccess, 'error': !isSuccess}">
      {{ submitStatus }}
    </div>

    <el-divider style="margin-top: 50px"></el-divider>
    <div style="padding: 0 30px" v-if="homeworkTopics.length !== 0 && hasSubmitted">
      <h3>作业批改记录</h3>
      <el-table :data="correctionRecord" style="width: 100%">
        <el-table-column label="题号" width="150%"><template v-slot="scope">{{scope.$index+1}}</template></el-table-column>
        <el-table-column prop="correctCondition" label="批改状态" width="200%">
          <el-button type="success" plain size="small" v-if="!isRecord" style="margin-top: 1px">已批改</el-button>
          <el-button type="info" plain size="small" v-if="isRecord" style="margin-top: 1px">未批改</el-button>
        </el-table-column>
        <el-table-column prop="correctJudgment" label="批改结果" width="200%"/>
        <el-table-column prop="teacherComments" label="老师评语"/>
      </el-table>
    </div>
  </div>
</template>

<style scoped>
li {
  list-style: none;
}

textarea {
  width: 90%;
}

.el-button {
  margin-top: 20px;
}

img {
  text-align: center;
  padding-left: 10%;
}

</style>
